import React, { useEffect, useState } from 'react'
import PageBreadcrumb from '../../components/PageBreadcrumb'
import {
  Card, Button, Row, Col, Table, Space, Popconfirm,
  Tag
} from 'antd'
import { RightOutlined } from '@ant-design/icons';
import { getRoles, deleteRoles, getRightsTree, deleteRightsById } from '../../api/roles'
import './roles.scss'
import Message from '../../components/Message';
import AddOrEditRole from './AddOrEditRole';
import SetRights from './SetRights';

const RolesList = () => {
  const text = '此操作将永久删除该权限, 是否继续?';
  const columns = [
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '角色描述',
      dataIndex: 'roleDesc',
      key: 'roleDesc',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type='link' onClick={() => handleEdit(record)}>编辑</Button>
          <Popconfirm placement="top" title={text} onConfirm={() => handleDelete(record.id)} okText="确定" cancelText="取消">
            <Button type='link'>删除</Button>
          </Popconfirm>
          <Button type='link' onClick={() => handleSetRights(record)}>分配权限</Button>
        </Space>
      ),
    },
  ];
  const [data, setData] = useState([]) // 列表数据
  const [loading, setLoading] = useState(false) // 加载
  const [isAddOrEdit, setIsAddOrEdit] = useState(false) // 控制对话框的显示和隐藏藏
  const [setRights, setSetRights] = useState(false)// 控制分配角色对话框的显示与隐藏
  const [roleInfo, setRoleInfo] = useState({}) // 当前权限信息
  const [rightsTree, setRightsTree] = useState([]) // 权限树

  useEffect(() => {
    getListData()
    getRightsTreeList()
  }, [])

  // 获取权限树
  const getRightsTreeList = async () => {
    const data = await getRightsTree();
    setRightsTree(data)
  };

  // 查询列表
  const getListData = async () => {
    setLoading(true)
    const data = await getRoles().finally(() => {
      setLoading(false)
    });

    setData(setExpandRowKey(data))
  };

  // 设置展开行key
  const setExpandRowKey = (oldData) => {
    let newData = [] //新数组
    oldData.map(item => {
      let _item = JSON.parse(JSON.stringify(item).replace('children', 'expandRow'));
      newData.push(_item)
    });
    return newData
  };

  // 点击编辑用户
  const handleEdit = (row) => {
    setRoleInfo({
      id: row.id,
      roleName: row.roleName,
      roleDesc: row.roleDesc,
    })
    setIsAddOrEdit(true)
  };

  // 删除
  const handleDelete = async (id) => {
    await deleteRoles(id);
    Message("success", "删除成功");
    getListData();
  };

  // 分配权限
  const handleSetRights = (row) => {
    let item = JSON.parse(JSON.stringify(row).replace('expandRow', 'children'));
    setRoleInfo(item)
    setSetRights(true)
  };

  // 根据id删除权限
  const removeRightsById = async (roleId, rightsId) => {
    await deleteRightsById(roleId, rightsId);
    Message("success", "删除成功");
    getListData();
  };

  // 关闭添加/编辑对话框
  const hideAddOrEdit = (type) => {
    setRoleInfo({})
    setIsAddOrEdit(false)
    if (type) {
      getListData()
    }
  }

  // 关闭分配权限对话框
  const hideSetRights = (type) => {
    setRoleInfo({})
    setSetRights(false)
    if (type) {
      getListData()
    }
  }

  const expandedRowRender = (children, roleId) => {
    return children.map((item1, index1) =>
      <Row key={item1.id} className={['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']}>
        <Col span={5}>
          <Popconfirm
            placement="top"
            title={text}
            onConfirm={() => removeRightsById(roleId, item1.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tag color="blue">{item1.authName}</Tag>
          </Popconfirm>
          <RightOutlined />
        </Col>
        <Col span={19}>
          {
            item1.children.map((item2, index2) =>
              <Row key={item2.id} className={[index2 === 0 ? '' : 'bdtop', 'vcenter']}>
                <Col span={6}>
                  <Popconfirm
                    placement="top"
                    title={text}
                    onConfirm={() => removeRightsById(roleId, item2.id)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Tag color="green">{item2.authName}</Tag>
                  </Popconfirm>
                  <RightOutlined />
                </Col>
                <Col span={18}>
                  {
                    item2.children.map(item3 =>
                      <Popconfirm
                        key={item3.id}
                        placement="top"
                        title={text}
                        onConfirm={() => removeRightsById(roleId, item3.id)}
                        okText="确定"
                        cancelText="取消"
                      >

                        <Tag color="orange">{item3.authName}</Tag>
                      </Popconfirm>
                    )
                  }
                </Col>
              </Row>
            )
          }
        </Col>
      </Row>
    )
  }

  return (
    <>
      <PageBreadcrumb>
        <span>权限管理</span>
        <span>角色列表</span>
      </PageBreadcrumb>

      <Card>
        <Row>
          <Col>
            <Button type="primary" onClick={() => setIsAddOrEdit(true)}>添加角色</Button>
          </Col>
        </Row>

        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          loading={loading}
          expandable={{
            expandedRowRender: record => <>{expandedRowRender(record.expandRow, record.id)}</>,
          }}
        />

      </Card>
      <AddOrEditRole visible={isAddOrEdit} roleInfo={roleInfo} onHide={hideAddOrEdit} />
      <SetRights visible={setRights} roleInfo={roleInfo} onHide={hideSetRights} rightsTree={rightsTree} />
    </>
  )
}

export default RolesList
